﻿using Catel;
using FluentValidation;
using System.IO;
using System.Text.RegularExpressions;
using YtbDownloader.Core.Interfaces;

namespace YtbDownloader.Validators;

public partial class ConfigValidator : AbstractValidator<IConfig>
{
    public ConfigValidator()
    {
        RuleFor(x => x.DownloadUrl).Must(IsValidDownloadUrl).WithMessage(LanguageHelper.GetRequiredString("CheckDownloadUrlMessage"));
        RuleFor(x => x.OutputPath).Must(Directory.Exists).WithMessage(LanguageHelper.GetRequiredString("CheckOutputDirMessage"));
        RuleFor(x => x.ProxyUrl).Must(IsValidProxyUrl).When(x => x.IsProxy).WithMessage(LanguageHelper.GetRequiredString("CheckProxyUrlMessage"));
        RuleFor(x => x.SubLang).NotEmpty().When(x => x.IsDownloadSub).WithMessage(LanguageHelper.GetRequiredString("CheckSubLangsMessage"));
        RuleFor(x => x.Cookies).Must(File.Exists).When(x => x.IsPassCookies).WithMessage(LanguageHelper.GetRequiredString("CookiesFileNoFoundMessage"));
        RuleFor(x => x.UserAgent).NotEmpty().When(x => x.IsCustomUserAgent).WithMessage(LanguageHelper.GetRequiredString("CustomUserAgentNoGoodHelpText"));
        RuleFor(x => x.ExtraArugments).NotEmpty().When(x => x.IsEnableExtraArugments).WithMessage(LanguageHelper.GetRequiredString("ExtraArugmentsNoGoodMessage"));
    }

    private static bool IsValidProxyUrl(string url)
    {
        return url != null && ProxyUrlRegex().IsMatch(url);
    }

    private static bool IsValidDownloadUrl(string url)
    {
        return url != null && DownloadUrlRegex().IsMatch(url);
    }

    [GeneratedRegex(@"^(http(s?)|socks\d)://([\w-]+\.)+[\w-]+:\d+(/[\w-./?%&=]*)?$")]
    private static partial Regex ProxyUrlRegex();

    [GeneratedRegex(@"^http(s?)://([\w-]+\.)+[\w-]+(/[\w-./?%&:=+#@]*)?$")]
    private static partial Regex DownloadUrlRegex();
}